package com.kingdee.shr.perf.web.handler.peopleSelf;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.ui.ModelMap;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
import com.kingdee.bos.dao.query.SQLExecutorFactory;
import com.kingdee.bos.metadata.entity.EntityViewInfo;
import com.kingdee.bos.metadata.entity.SelectorItemCollection;
import com.kingdee.bos.metadata.entity.SelectorItemInfo;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.hr.perf.EvalPersonFactory;
import com.kingdee.eas.hr.perf.EvalPersonInfo;
import com.kingdee.eas.hr.perf.EvalRelationDetailFactory;
import com.kingdee.eas.hr.perf.EvalRelationDetailInfo;
import com.kingdee.eas.hr.perf.GradeModeInfo;
import com.kingdee.eas.hr.perf.ITestPageForm;
import com.kingdee.eas.hr.perf.MultiDimEvaluatorInfo;
import com.kingdee.eas.hr.perf.MultiDimentionSolutionPeriodInfo;
import com.kingdee.eas.hr.perf.TestPageFormFactory;
import com.kingdee.eas.hr.perf.TestPageFormInfo;
import com.kingdee.eas.hr.perf.TestPaperInfo;
import com.kingdee.jdbc.rowset.IRowSet;
import com.kingdee.shr.base.syssetting.context.SHRContext;
import com.kingdee.shr.base.syssetting.exception.SHRWebException;
import com.kingdee.shr.base.syssetting.web.json.JSONUtils;
import com.kingdee.util.StringUtils;

/**
 * @Copyright 版权所有：天津金蝶软件有限公司 <br>
 *            Title: MDassessTargetEvaluEditHandlerEx <br>
 *            Description: 360绩效考核 批量提交
 * @author yacong_liu Email:yacong_liu@kingdee.com
 * @date 2019-3-4 & 下午02:50:08
 * @since V1.0
 */
public class MDassessTargetEvaluEditHandlerEx extends MDassessTargetEvaluEditHandler {

    private String evalPersonID;

    private String testPaperID;

    private String solutionPeriodID;

    private String mdObjectID;

    private String mdEvaluatorID;

    private String evalReDetailID;

    protected String assignmentId;

    private BigDecimal maxGrade;

    private BigDecimal minGrade;

    private Context ctx;

    private ITestPageForm iTestPageForm;

    public MDassessTargetEvaluEditHandlerEx(Context ctx) {
        this.ctx = ctx;
    }

    public MDassessTargetEvaluEditHandlerEx() {
        this.ctx = SHRContext.getInstance().getContext();
    }

    /**
     * 
     * <p>
     * Title: bantchSubmitTargetRealAction
     * </p>
     * <p>
     * Description: 批量提交考核分数
     * </p>
     * 
     * @param request
     * @param response
     * @param modelMap
     * @throws SHRWebException
     */
    public void bantchSubmitTargetRealAction(HttpServletRequest request, HttpServletResponse response,
            ModelMap modelMap) throws SHRWebException {

        HashMap resultMsg = new HashMap();

        String assignmentIds = request.getParameter("assignmentIds");
        String[] ids = assignmentIds.split(",");
        if (ids.length <= 0) {
            return;
        }

        boolean flag = false;
        try {
            for (int i = 0; i < ids.length; i++) {

                // 提交前校验 是否已保存
                iTestPageForm = (iTestPageForm != null) ? iTestPageForm : TestPageFormFactory
                        .getRemoteInstance();

                boolean exists = iTestPageForm.exists("where evalPerson = '" + ids[i] + "'");
                TestPageFormInfo testPageFormInfo = null;
                if (exists) {

                    testPageFormInfo = iTestPageForm.getTestPageFormInfo(" where evalPerson = '" + ids[i]
                            + "'");
                    if (testPageFormInfo == null) {
                        continue;
                    }

                    // 处理时间 保存后的数据处理时间为空 提交后不为空
                    Date processTime = testPageFormInfo.getProcessTime();
                    if (processTime == null) {
                        // 考核问卷已保存可以 提交考核分数

                        submitTargetReal(response, ids[i]);
                        flag = true;
                    }
                }

            }

            if (flag) {
                resultMsg.put("opResult", "ok");
            } else {
                resultMsg.put("opResult", "nodata");
            }

            JSONUtils.SUCCESS(resultMsg);
        } catch (EASBizException e) {
            e.printStackTrace();
            resultMsg.put("opResult", "no");
            resultMsg.put("msg", "提交失败");
            JSONUtils.writeJson(response, resultMsg);
        } catch (BOSException e) {
            e.printStackTrace();
            resultMsg.put("opResult", "no");
            resultMsg.put("msg", "提交失败");
            JSONUtils.writeJson(response, resultMsg);
        }

    }

    /**
     * 
     * <p>
     * Title: submitTargetReal
     * </p>
     * <p>
     * Description: 提交考核分数
     * </p>
     * 
     * @param response
     * @param assignmentId
     * @throws SHRWebException
     * @throws BOSException
     * @throws EASBizException
     */
    private void submitTargetReal(HttpServletResponse response, String assignmentId) throws SHRWebException,
            EASBizException, BOSException {

        if (StringUtils.isEmpty(assignmentId)) {
            return;
        }

        // HashMap resultMsg = new HashMap();

        setMDEvaluTaskParam(assignmentId);

        TestPageFormInfo tfInfo = null;
        try {
            tfInfo = TestPageFormFactory.getRemoteInstance().getTestPageForm(this.evalPersonID,
                    this.solutionPeriodID, this.mdObjectID, this.testPaperID);
        } catch (EASBizException e) {
            e.printStackTrace();
        } catch (BOSException e) {
            e.printStackTrace();
        }

        BigDecimal score = tfInfo.getScore();
        score.setScale(6, 4);
        BigDecimal soluScore = null;

        BigDecimal zero = new BigDecimal("0.000000");
        TestPaperInfo tpInfo = tfInfo.getTestPaper();
        this.minGrade = tpInfo.getGradeMode().getMinGrade();
        this.minGrade.setScale(6, 4);
        this.maxGrade = tpInfo.getGradeMode().getMaxGrade();
        this.maxGrade.setScale(6, 4);

        MultiDimentionSolutionPeriodInfo info = tfInfo.getMdEvaluResult().getSolutionPeriod();
        GradeModeInfo soluGradeMode = info.getMDSolution().getGradeMode();
        if (soluGradeMode != null) {
            soluGradeMode.getMaxGrade().setScale(6, 4);
            soluGradeMode.getMinGrade().setScale(6, 4);
        }
        String rankID = null;
        if (tfInfo.getRank() != null) {
            rankID = tfInfo.getRank().getId().toString();
        }
        soluScore = zero.add(score.subtract(this.minGrade)).divide(this.maxGrade.subtract(this.minGrade), 4);
        soluScore = soluScore.multiply(soluGradeMode.getMaxGrade().subtract(soluGradeMode.getMinGrade()))
                .add(soluGradeMode.getMinGrade());

        EvalPersonFactory.getRemoteInstance().saveFormData(tfInfo, this.evalPersonID, soluScore, rankID,
                this.mdEvaluatorID, this.evalReDetailID, this.solutionPeriodID, this.mdObjectID);
        /*
         * try { EvalPersonFactory.getRemoteInstance().saveFormData(tfInfo, this.evalPersonID,
         * soluScore, rankID, this.mdEvaluatorID, this.evalReDetailID, this.solutionPeriodID,
         * this.mdObjectID); resultMsg.put("opResult", "ok"); JSONUtils.SUCCESS(resultMsg); } catch
         * (EASBizException e1) { e1.printStackTrace(); resultMsg.put("opResult", "no");
         * resultMsg.put("msg", "提交失败"); JSONUtils.writeJson(response, resultMsg); } catch
         * (BOSException e1) { e1.printStackTrace(); resultMsg.put("opResult", "no");
         * resultMsg.put("msg", "提交失败"); JSONUtils.writeJson(response, resultMsg); }
         */
    }

    private void setMDEvaluTaskParam(String evaluPersonID) {
        EvalPersonInfo eval = null;
        try {
            EntityViewInfo ev = new EntityViewInfo();
            SelectorItemCollection coll = new SelectorItemCollection();
            ev.setSelector(coll);
            coll.add(new SelectorItemInfo("id"));
            coll.add(new SelectorItemInfo("evalReDetail.id"));
            coll.add(new SelectorItemInfo("evalReDetail.mdEvaluator.id"));
            coll.add(new SelectorItemInfo("evalReDetail.mdEvaluator.solutionPeriod.id"));
            coll.add(new SelectorItemInfo("evalReDetail.mdEvaluator.multiDimObject.id"));
            coll.add(new SelectorItemInfo("evalReDetail.evalRelation.paper.id"));
            coll.add(new SelectorItemInfo("evalReDetail.evalRelation.id"));
            coll.add(new SelectorItemInfo("mdEvaluator.id"));
            eval = EvalPersonFactory.getRemoteInstance().getEvalPersonInfo(new ObjectUuidPK(evaluPersonID),
                    coll);
        } catch (EASBizException e) {
        } catch (BOSException e) {
        }
        EvalRelationDetailInfo detailInfo = eval.getEvalReDetail();
        MultiDimEvaluatorInfo evalutorInfo = detailInfo.getMdEvaluator();
        String evalutorID = evalutorInfo.getId().toString();
        String solutionPeriodId = evalutorInfo.getSolutionPeriod().getId().toString();
        String objectID = evalutorInfo.getMultiDimObject().getId().toString();
        String detailID = detailInfo.getId().toString();
        String paperId = detailInfo.getEvalRelation().getPaper().getId().toString();
        try {
            SelectorItemCollection sic = new SelectorItemCollection();
            sic = new SelectorItemCollection();
            sic.add(new SelectorItemInfo("id"));
            sic.add(new SelectorItemInfo("evalRelation.id"));
            sic.add(new SelectorItemInfo("evalRelation.paper.id"));
            EvalRelationDetailInfo erdi = EvalRelationDetailFactory.getRemoteInstance()
                    .getEvalRelationDetailInfo(new ObjectUuidPK(detailID), sic);

            String evaluRelationID = eval.getEvalReDetail().getEvalRelation().getId().toString();
            StringBuffer sql = new StringBuffer(
                    "select FPaperQuestID from T_PF_EvalurelationQuest WHERE fsolutionPeriodid ='");
            sql.append(solutionPeriodId).append("' AND FEvalRelationID ='").append(evaluRelationID).append(
                    "' AND FEvalPerson='").append(eval.getId().toString()).append("'");
            IRowSet result = SQLExecutorFactory.getRemoteInstance(sql.toString()).executeSQL();
            if (result.next()) {
                paperId = result.getString("FPaperQuestID");
            } else if ((erdi != null) && (erdi.getEvalRelation() != null)
                    && (erdi.getEvalRelation().getPaper() != null))
                paperId = erdi.getEvalRelation().getPaper().getId().toString();
        } catch (EASBizException e) {
        } catch (Exception e) {
        }
        this.evalPersonID = evaluPersonID;
        this.solutionPeriodID = solutionPeriodId;
        this.mdObjectID = objectID;
        this.testPaperID = paperId;
        this.evalReDetailID = detailID;
        this.mdEvaluatorID = evalutorID;
    }

}
